const jwt = require('jsonwebtoken');
const secret = require('../../config/secret');
class Share {
    /**
     * 扫码洗车
     * @api {POST}        /share                分享
     * @apiName           /share
     * @apiGroup          Share
     * @apiParam          {String}         token       分享
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {}
       }
     */
    async share(ctx) {
        const {
            db,
            model,
            request: {
                body: { token }
            },
            user: { User }
        } = ctx;

        let verify = jwt.verify(token, secret.program, (error, decoded) => {
            if (error) {
                return false;
            }
            return decoded;
        });

        if (!verify) {
            ctx.errors('服务器错误');
            console.log('空');
            return;
        }
        console.log(verify);

        // 查询分享限制
        const share = await db.Setting.findOne();
        // 服务器奖励次数
        const reward = await db.Giving.findOne({ where: { type: -1 } });
        // 查询爸爸领取奖励次数
        const count = await db.Reward.count({
            where: { userId: verify.User.id }
        });
        const childrenCount = await db.Children.count({
            where: { childrenId: User.id }
        });
        const a = await db.Reward.count({ where: { userId: User.id } });
        const b = await db.Reward.count({
            where: { userId: verify.User.id, givingId: User.id }
        });
        const c = await db.Reward.count({
            where: { userId: User.id, givingId: verify.User.id }
        });
        if (b) {
            console.log('你们俩， 之前领取过奖励');
        } else if (c) {
            console.log('你们俩， 之前领取过奖励');
        } else if (count >= share.share) {
            //如果爸爸领取次数超过限制，就不给他领取
            console.log(
                '爸爸 ' + verify.User.id + '最多领取' + share.share + '次'
            );
            // 儿子之前是否邀请过别人
            if (a >= share.share) {
                console.log('儿子， 你之前领取过奖励');
            } else if (childrenCount >= share.share) {
                // 儿子超过奖励次数
                console.log(
                    '儿子 ' + User.id + '最多领取' + share.share + '次'
                );
            } else {
                let transaction;
                let childrenUser = await db.User.findOne({
                    where: { id: User.id }
                });

                if (childrenUser.parentId !== 0) {
                    console.log('儿子你已经注册了一次');
                    return;
                }

                try {
                    transaction = await model.transaction();
                    // 儿子没超过奖励次数
                    await db.Children.upsert({
                        childrenId: User.id,
                        parentId: verify.User.id,
                        day: 1,
                        limit: 1
                    });
                    await db.User.update(
                        {
                            reward: childrenUser.reward + reward.limit,
                            parentId: verify.User.id
                        },
                        { where: { id: User.id } }
                    );
                    await transaction.commit();
                    console.log('儿子领取奖励成功');
                } catch (e) {
                    console.log(e);
                    await transaction.rollback();
                    ctx.errors('errors');
                    return;
                }
            }
        } else {
            let transaction;
            try {
                transaction = await model.transaction();

                let parentUser = await db.User.findOne({
                    where: { id: verify.User.id }
                });
                let childrenUser = await db.User.findOne({
                    where: { id: User.id }
                });
                //爸爸领取奖励
                await db.User.update(
                    { reward: parentUser.reward + reward.limit },
                    { where: { id: verify.User.id } }
                );
                //判断儿子领取奖励次数
                if (childrenCount >= share.share) {
                    // 儿子超过奖励次数
                    console.log(
                        '儿子 ' + User.id + '最多领取' + share.share + '次'
                    );
                } else if (childrenUser.parentId !== 0) {
                    console.log('儿子你已经注册了一次');
                } else {
                    // 儿子领取奖励
                    await db.User.update(
                        {
                            reward: childrenUser.reward + reward.limit,
                            parentId: verify.User.id
                        },
                        { where: { id: User.id } }
                    );
                    // 记录儿子领取奖励
                    await db.Children.upsert({
                        childrenId: User.id,
                        parentId: verify.User.id,
                        day: 1,
                        limit: 1
                    });
                    console.log('儿子领取奖励成功');
                }
                // 记录爸爸领取奖励
                await db.Reward.upsert({
                    userId: verify.User.id,
                    givingId: User.id,
                    day: 1,
                    limit: 1
                });
                await transaction.commit();
                console.log('爸爸领取奖励成功');

                ctx.success();
            } catch (e) {
                console.log(e);
                await transaction.rollback();
                ctx.errors('errors');
                return;
            }
        }
    }
}
module.exports = new Share();
